<template>
  <div class="add-date-menu" v-if="getMonth.length">
    <div class="adm-item" v-for="(data, index) in containerList" :key="data.day" v-loading="priceLoading">
      <p class="adm-item-day">{{ data.week }}({{ data.send_at }})</p>
      <div class="adm-item-content">
        <div class="ic-top jc-sb">
          <div class="ic-top-btn">
            <el-button :disabled="!isEdit" @click="addMeal(data, index)">新增套餐</el-button>
            <el-button :disabled="!isEdit" @click="addGood(data, index)">新增商品</el-button>
          </div>
          <div class="ic-top-right align-center">
            <p>数量小计(份): {{ data.allNum }}</p>
            <p class="mg-l-10">价格小计(元): {{ data.allPrice }}</p>
          </div>
        </div>
        <div class="ic-bottom">
          <div v-for="(shopItem, shopIndex) in data.dataList" :key="shopItem.indexKey" class="align-center shop-item">
            <div v-if="shopItem.type == 'goods'" class="jc-sb">
              <el-autocomplete
                :disabled="!isEdit"
                class="inline-input wid180"
                v-model="shopItem.goods_spu_name"
                clearable
                ref="searchSelect"
                :fetch-suggestions="
                  (queryString, cb) => {
                    querySearchAsync(queryString, cb, '1');
                  }
                "
                placeholder="请输入商品"
                :trigger-on-focus="false"
                @select="item => { handleSelect(data, shopItem, item, 1) }"
                >
                  <template slot-scope="{ item }">
                    <div class="main_name" :style="{opacity:(item.is_inventory==2 && isInventory)?0.5:1}">
                      <span class="flex-btw">
                        <span> {{ item.goods.name }}【{{ item.spu_name ? item.spu_name.title : "" }}】</span>
                      </span>
                    </div>
                  </template>
              </el-autocomplete>
              <div v-if="shopItem.goods_spu_id" class="goods-contaier align-center">
                <p class="good-name">{{ shopItem.name }}</p>
                <el-input :disabled="!isEdit" type="number" v-model="shopItem.num" @input="validateInput(shopItem, $event)" @change="getAllPrice(data)"></el-input>
                <p class="width80 align-right">{{ shopItem.price }}/{{ shopItem.unit }}</p>
                <p class="width80 mg-l-10">{{ (shopItem.price * shopItem.num).toFixed(2) }}</p>
              </div>
              <p v-if="isEdit" class="delete-shop" @click="deleteGood(index, shopIndex, data)">X</p>
            </div>
            <div v-else class="packgae-wrap">
              <el-autocomplete
                :disabled="!isEdit"
                class="inline-input wid180"
                v-model="shopItem.name"
                clearable
                ref="searchSelect"
                :fetch-suggestions="
                  (queryString, cb) => {
                    querySearchAsync(queryString, cb, '3');
                  }
                "
                placeholder="请输入套餐"
                :trigger-on-focus="false"
                @select="item => { handleSelect(data, shopItem, item) }"
                >
                  <template slot-scope="{ item }">
                    <div class="main_name" :style="{opacity:(item.is_inventory==2 && isInventory)?0.5:1}">
                      <span>{{ item.name }}</span>
                    </div>
                  </template>
              </el-autocomplete>
              <template v-if="shopItem.package_goods_id && shopItem.package_goods.length">
                <div class="package-goods">
                  <div class="goods-contaier align-center" v-for="packageItem in shopItem.package_goods" :key="packageItem.goods_spu_id">
                    <p class="good-name">{{ packageItem.name }}</p>
                    <el-input :disabled="!isEdit" type="number" v-model="packageItem.num" @input="validateInput(packageItem, $event)" @change="getAllPrice(data)"></el-input>
                    <p class="width80 align-right">{{ packageItem.price }}/{{ packageItem.unit }}</p>
                    <p class="width80 mg-l-12">{{ (packageItem.price * packageItem.num).toFixed(2) }}</p>
                  </div>
                </div>
              </template>
              <p v-if="isEdit" class="delete-shop mg-t-5" @click="deleteGood(index, shopIndex, data)">X</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs';
import { getInfo } from '@/api/menu.js'
import { goods_getAllGoodsSpu, goods_getGoodsSpu } from "@/api/currency";
import { turnoverOrder_searchItems } from "@/api/warehouse/warehouseTurnOrder.js";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
export default {
  props: {
    dateTimes: {
      type: Array,
      default: () => []
    },
    isEdit: {
      type: Boolean
    }
  },
  data() {
    return {
      containerList: [],
      allContainerList: {},
      isInventory: false,
      priceLoading: false
    }
  },
  computed: {
    getMonth() {
      if(!this.dateTimes.length) return false
      const dateRange = [];
      if (this.dateTimes[1] && this.dateTimes[0] && dayjs(this.dateTimes[1]).diff(this.dateTimes[0], 'day') > 6) {
      }else {
        if(this.containerList.length) {
          this.containerList.forEach(el => {
            this.allContainerList[el.send_at] = JSON.parse(JSON.stringify(el))
          })
        }
        // 使用dayjs遍历时间段内的每一天
        let current = dayjs(this.dateTimes[0]);
        const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        while (current.isBefore(this.dateTimes[1]) || current.isSame(this.dateTimes[1])) {
          dateRange.push({
            send_at: current.format('YYYY-MM-DD'),
            week: weekdays[current.day()],
            dataList: [],
            allPrice: "",
            allNum: "",
          });
          current = current.add(1, 'day');
        }
      }
      this.containerList = dateRange.map(el => {
        if(this.allContainerList[el.send_at]) {
          el.dataList = this.allContainerList[el.send_at].dataList  
          el.allPrice = this.allContainerList[el.send_at].allPrice  
          el.allNum = this.allContainerList[el.send_at].allNum  
        }
        return el
      })
      console.log(this.allContainerList, 'this.allContainerList');
      return dateRange
    }
  },
  methods: {
    getMenuList(params) {
      return new Promise((resovle, reject) => {
        getInfo('/packageMenu/packagelist', params).then(res => {
          if(res.errcode == 0) {
            resovle(res)
          }else {
            reject()
          }
        }).catch(err => {
          reject(err)
        })
      })
    },
    querySearchAsync(queryString, cb, url, item) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, { name: queryString.trim() })
            ) + apiUrl().appsecret
          )
        },
        apiUrl().name,
        {
          name: queryString.trim(),
          allow_below_shelf: this.url == 1 ? 1 : ""
        }
      );

      if(this.isPurchase == 1) {
        data.is_purchase = this.isPurchase;
      }

      if (url != 1) {
        delete data.allow_below_shelf;
      }

      let func = null;
      switch (url) {
        case "1":
          func = goods_getGoodsSpu;
          break;
        case "2":
          func = turnoverOrder_searchItems;
          break;
        case "3":
          func = this.getMenuList;
          break;
        default:
          func = goods_getAllGoodsSpu;
          break;
      }
      func(data).then(res => {
        if (res.errcode == 0) {
          let results = [];
          if(url == 3) {
            results = res.data
          } else {
            res.data.goods.map(e => {
              let title = e.spu_name ? e.spu_name.title : "";
              e.name = e.goods.name + "【" + title + "】";
            });
            results = res.data.goods;
          }
          if (this.$refs.searchSelect) {
            this.$refs.searchSelect.activated = true;
          }
          cb(results);
        } else {
          this.$message.error(res.errmsg);
          cb([]);
        }
      });
    },
    handleSelect(goodsData, item, data, url) {
      if(item.is_inventory==2 && this.isInventory){
        this.$message.error('此商品为调拨商品')
        return
      }
      if(url == 1) {
        this.sendValue(item, data, goodsData)
      }else {
        this.sendMenuValue(item, data, goodsData)
      }
    },
    changeList(list) {
      this.allContainerList = list
      this.containerList = this.containerList.map(el => {
        if(this.allContainerList[el.send_at]) el.dataList = this.allContainerList[el.send_at]
        return el
      })
      this.$nextTick(() => {
        this.containerList.forEach(el => {
          this.getAllPrice(el)
        })
      })
    },
    addMeal(item, index) {  //  新增套餐
      this.containerList[index].dataList.push({
        name: '',
        type: 'package_goods',
        package_goods_id: '',
        num: '',
        package_goods: [],
        goods_spu_name: '',
        allPrice: '',
        allNum: '',
        indexKey: new Date().getTime()
      })
    },
    addGood(item, index) {  //  新增商品
      this.containerList[index].dataList.push({
        name: '',
        type: 'goods',
        goods_spu_id: '',
        price: '',
        unit: '',
        num: '',
        goods_spu_name: '',
        allPrice: '',
        allNum: '',
        indexKey: new Date().getTime()
      })
    },
    clearInput(item, index, shopIndex) {
      // this.containerObj[index].name = ''
      item.name = ''
      item.goods_spu_id = ''
    },
    sendValue(item, data, goodsData) { //  商品下拉框选择
      item.goods_spu_id = data.id
      item.goods_spu_name = data.goods.name + '【' + data.spu_name.title + '】'
      item.name = data.goods.name
      item.price = data.market_price
      item.num = 1
      item.unit = data.spu_unit.title
      this.getAllPrice(goodsData)
    },
    sendMenuValue(item, data, goodsData) {  //  套餐下拉框选择
      item.name = data.name;
      item.package_goods_id = data.id
      getInfo('/packageGoods/packageGoodslist', {
        package_goods_id: data.id
      }).then(res => {
        item.package_goods = res.data.map(el => {
          return {
            goods_spu_id: el.goods_spu_id,
            name: el.goods_name,
            price: el.market_price,
            num: el.num || 1,
            unit: el.unit_name
          }
        })
        this.getAllPrice(goodsData)
      })
    },
    validateInput(row, value) {
      if(!value) {
        row.num = 0
      }else {
        const reg = /^\D*([0-9]\d*\.?\d{0,2})?.*$/
        row.num = String(value).replace(reg, '$1')
      }
      return 
    },
    getAllPrice(item) { //  计算价格小计
      this.priceLoading = true
      let count = ''
      const that = this
      if(item.dataList.length) {
        async function change() {
          const goodsList = item.dataList.filter(el => el.price && el.type === 'goods')
          const menuList = item.dataList.filter(el => el.package_goods_id && el.type !== 'goods' && el.package_goods.length)
          let goodCount = 0
          if(goodsList.length) {
            const list = goodsList.map(el => {
              return (el.price * el.num).toFixed(2)
            })
            if(list.length) {
              await getInfo('/common/verb', {
                data: list.join(','),
                noun: 1
              }, 'post').then(res => {
                goodCount = res.data
              })
            }
          }
          let menuLists = []
          let menuCount = 0
          if(menuList.length) {
            menuLists = menuList.map(el=> el.package_goods).flat()
            const list = menuLists.map(el => {
              return (el.price * el.num).toFixed(2)
            })
            if(list.length) {
              await getInfo('/common/verb', {
                data: list.join(','),
                noun: 1
              }, 'post').then(res => {
                menuCount = res.data
              })
            }
          }
          await getInfo('/common/verb', {
            data: `${goodCount},${menuCount}`,
            noun: 1
          }, 'post').then(res=> {
            that.priceLoading = false
            item.allPrice = res.data;
            that.$set(item, 'allPrice', res.data)
          })
          const goodsNum = eval(goodsList.map(el => el.num).join('+')) || 0
          const menuNum = eval(menuLists.map(el => el.num).join('+')) || 0
          getInfo('/common/verb', {
            data: `${goodsNum},${menuNum}`,
            noun: 1
          }, 'post').then(res=> {
            that.priceLoading = false
            item.allNum = res.data;
            that.$set(item, 'allNum', res.data)
          })
        }
        change()
      }else {
        this.priceLoading = false
        item.allPrice = '';
        item.allNum = '';
      }
      return count
    },
    getAllNum(item) { //  计算数量小计
      let allNum = ''
      if(item.dataList.length) {
        const goodsList = item.dataList.filter(el => el.price && el.type === 'goods')
        const menuList = item.dataList.filter(el => el.package_goods_id && el.type !== 'goods' && el.package_goods.length)
        let menuLists = []
        if(menuList.length) {
          menuLists = menuList.map(el=> el.package_goods).flat()
        }
        const goodsNum = eval(goodsList.map(el => el.num).join('+')) || 0
        const menuNum = eval(menuLists.map(el => el.num).join('+')) || 0
        getInfo('/common/verb', {
          data: `${goodsNum},${menuNum}`,
          noun: 1
        }, 'post').then(res=> {
          this.priceLoading = false
          item.allNum = res.data;
          this.$set(item, 'allNum', res.data)
        })
        allNum = goodsNum + menuNum
      }
      return allNum + '份'
    },
    deleteGood(index, shopIndex, data) {
      this.containerList[index].dataList.splice(shopIndex, 1);
      this.getAllPrice(data)
    }
  }
}
</script>

<style lang="scss" scoped>
$border-color: #EBEEF5;
.add-date-menu {
  font-size: 14px;
  margin-top: 16px;
  display: flex;
  align-items: stretch;
  overflow-x: auto;
  overflow-y: hidden;
  border-bottom: 1px solid $border-color;
  .mg-t-5 {
    margin-top: 5px;
  }
  .mg-l-12 {
    margin-left: 12px;
  }
  .adm-item {
    width: 620px;
    flex-shrink: 0;
    &:first-child {
      .adm-item-day {
        border-left: 1px solid $border-color;
      }
    }
    &:last-child {
      .adm-item-day {
        border-right: 1px solid $border-color;
      }
    }
    .adm-item-day {
      height: 44px;
      line-height: 44px;
      background: #F6F8F9;
      border-radius: 0px 0px 0px 0px;
      border: 1px solid $border-color;
      text-align: center;
      border-right: 0;
      border-left: 0;
    }
    .adm-item-content {
      border-right: 1px solid $border-color;
      min-height: 300px;
      height: calc(100% - 44px);
      .ic-top {
        padding: 0 20px 0 6px;
        height: 48px;
        line-height: 48px;
        border-bottom: 1px solid $border-color;
        .el-button {
          border-color: #03A98E;
          color: #03A98E;
          &:hover {
            background-color: rgba(3,169,142,0.2);
          }
          &.is-disabled {
            border-color: #EBEEF5;
            color: #C0C4CC;
            &:hover {
              background-color: transparent;
            }
          }
        }
      }
      .ic-bottom {
        padding: 0 0 0 6px;
        .jc-sb {
          width: 100%;
          padding: 0 20px 0 0;
           /deep/.el-input {
            .el-input__inner {
              padding: 0 0 0 15px;
            }
          }
        }
      }
      .shop-item {
        padding: 8px 0;
        border-bottom: 1px solid $border-color;
      }
      .goods-contaier {
        margin-left: 20px;
        justify-content: space-between;
        .el-input {
          width: 100px;
        }
        .good-name {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          width: 100px;
        }
        .width80 {
          width: 80px;
        }
        .align-right {
          text-align: right;
        }
      }
    }
    .packgae-wrap {
      display: flex;
      width: 100%;
      padding: 0 20px 0 0;
      justify-content: space-between;
      /deep/.el-input {
        .el-input__inner {
          padding: 0 0 0 15px;
        }
      }
      .package-goods {
        .goods-contaier {
          margin-top: 9px;
          &:first-child {
            margin-top: 0;
          }
        }
      }
    }
    .delete-shop {
      font-size: 16px;
      font-weight: bold;
      color: rgba(0,0,0,0.35);
      cursor: pointer;
    }
  }
  .jc-sb {
    justify-content: space-between;
  }
  .align-center, .jc-sb  {
    display: flex;
    align-items: center;
  }
  .inline-input {

  }
}
</style>